package com.smile.auth.controller;

import com.alibaba.fastjson.JSON;
import com.smile.auth.feign.MemberFeignService;
import com.smile.auth.vo.OAuth2Vo;
import com.smile.common.utils.HttpUtils;
import com.smile.common.utils.R;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code) throws Exception {

        //获得code后 封装调用参数换取 access_token
        Map<String, String> map = new HashMap<>();
        map.put("client_id","4055447732");
        map.put("client_secret","315ac88913a1ce95934a284e23be59a2");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.smile.com/oauth2.0/weibo/success");
        map.put("code",code);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());

        //获取响应结果
        if(response.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(response.getEntity());
            //将返回的结果封装成指定Vo
            OAuth2Vo oAuth2Vo = JSON.parseObject(json, OAuth2Vo.class);

            R r = memberFeignService.oauthLogin(oAuth2Vo);

            if(r.getCode()==0){

            }

            //登录成功后跳回首页
            return "redirect:http://smile.com/";
        }else {
            //登录失败返回登录页
            return "redirect:http://auth.smile.com/";
        }



    }
}
